package commLogger

import (
	"encoding/json"
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedis"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisList"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Json"
	"time"
)

const redisConsoleKey = "fox-edge:service:console:public"

type redisConsoleService struct {
	redisList commRedisList.RedisListService
}

func (e *redisConsoleService) GetAll() ([]map[string]interface{}, error) {
	list, err := e.redisList.GetAll(redisConsoleKey)
	if err != nil {
		return nil, err
	}

	result := make([]map[string]interface{}, 0)
	for _, jsn := range list {
		data := Json.BuildMapByJson(jsn)
		result = append(result, data)
	}

	return result, nil
}

func (e *redisConsoleService) GetRang(start int64, end int64) ([]map[string]interface{}, error) {
	list, err := e.redisList.GetRange(redisConsoleKey, start, end)
	if err != nil {
		return nil, err
	}

	result := make([]map[string]interface{}, 0)
	for _, jsn := range list {
		data := Json.BuildMapByJson(jsn)
		result = append(result, data)
	}

	return result, nil
}

func (e *redisConsoleService) Size() (int64, error) {
	return e.redisList.Size(redisConsoleKey)
}

func (e *redisConsoleService) Error(value interface{}) error {
	return e.out("ERROR", value)
}

func (e *redisConsoleService) Info(value interface{}) error {
	return e.out("INFO", value)
}

func (e *redisConsoleService) Warn(value interface{}) error {
	return e.out("WARN", value)
}

func (e *redisConsoleService) Debug(value interface{}) error {
	return e.out("DEBUG", value)
}

func (e *redisConsoleService) out(level string, value interface{}) error {
	data := e.build(level, value, time.Now().UnixMilli())

	code, err := json.Marshal(data)
	if err != nil {
		return err
	}
	jsn := string(code)

	if commRedis.Client == nil {
		return errors.New("尚未与redis建立连接")
	}

	err = e.redisList.KPush(redisConsoleKey, jsn)
	if err != nil {
		return err
	}
	return nil
}

func (e *redisConsoleService) build(level string, value interface{}, time int64) map[string]interface{} {
	data := make(map[string]interface{})
	data["serviceType"] = commEnv.Service.ServiceType
	data["serviceName"] = commEnv.Service.ServiceName
	data["createTime"] = time
	data["level"] = level
	data["value"] = value

	return data
}
